<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Admin extends MY_Controller {
    
    public function __construct() {
        parent::__construct();
        $this->load->model('setting_model');
        $this->load->model('role_model');
        $this->load->model('user_profiles');
        $this->load->model('tree_model');
        
        $this->load->helper('url');
        $this->load->library('table');
        
        if (!$this->role_model->isAdminRole()){
            redirect(''); // the user is not admin, redirect them!
        }
        
    }

    /**!!!
     * 
     * 
     */
    public function index(){
        $data['title'] = "Панель администратора";
        $data['content'] = '<h2 class="sub-header">Пользователи</h2><div class="table-responsive">';
        $data['content'] .= $this->user_profiles->get_users_table();
        $data['content'] .= '</div>';
        
        $this->load->view('ver2/admin_view',$data);
    }
    
    public function roles(){
        $data['title'] = "Панель администратора";
        $data['content'] = '<h2 class="sub-header">Роли</h2><div class="table-responsive">';
        $data['content'] .= $this->role_model->get_roles_table();
        $data['content'] .= '</div>';
//        $data['role_list'] = $this->role_model->get_all_roles();
        $data['role_tree'] = $this->tree_model->get_tree_directory_with_chek();
        
        $this->load->view('ver2/admin_view',$data);
    }
    

    public function ajax(){
        if (!isset($this->session->userdata['login']) || $this->session->userdata['login'] == NULL || $this->session->userdata('logged_in') != TRUE){
            $this->session->sess_destroy();
            header('HTTP/1.0 401 Unauthorized');
            exit ();
        }elseif($this->session->userdata['role'] != 2){
            header('HTTP/1.0 403 Forbidden');
            exit ();
        }

        $func = $this->uri->segment(3);
//        $str = replace_quotes($_SERVER['QUERY_STRING']);
        $str = replace_quotes(filter_input(INPUT_SERVER,'QUERY_STRING'));
        $get = array();
        parse_str($str,$get);
        
        $result = FALSE;
        
        switch ($func) {
            case 'add_user': //добавить пользователя
                $result = $this->user_profiles->add_new_user($get['userLogin'], $get['userDomain'],$get['userDescription']);
                $this->print_json($result);
                break;
            case 'upd_user': //обновить пользователя
                $result = $this->user_profiles->update_user($get['userID'],$get['userLogin'], $get['userDomain'],$get['userRole'],$get['userDescription']);
                if(isset($get['userUpTrash'])){
                    $rr = $this->user_profiles->clear_up_trash($get['userID']);
                    log_message("debug", "\n\nuser clear_up_trash -> ".$rr." rows\n\n");
                }
                $this->print_json($result);
                break;
            case 'delete_user': //удалить пользователя
                $result = $this->user_profiles->delete_user($get['userID']);
                $this->print_json($result);
                break;
            case 'add_role': //добавить роль
                $result = $this->role_model->add_role($get['roleName'], $get['roleDescription']);
                $this->print_json($result);
                break;
            case 'delete_role': //удалить роль
                $result = $this->role_model->delete_role($get['roleID']);
                $this->print_json($result);
                break;
            case 'upd_role': //обновить роль
//                log_message("debug", "post " . print_r($_POST,true));
                $result = $this->role_model->upd_role(
                        filter_input(INPUT_POST, 'roleID'),
                        filter_input(INPUT_POST, 'roleName'),
                        filter_input(INPUT_POST, 'roleDescription'),
                        filter_input(INPUT_POST, 'roleKeys'),
                        filter_input(INPUT_POST, 'startDate'),
                        filter_input(INPUT_POST, 'endDate'));
                
                $trash = '';
                if(filter_input(INPUT_POST, 'roleUpTrash')){
                    $rr = $this->role_model->clear_up_trash( filter_input(INPUT_POST, 'roleID'));
                    log_message("debug", "\n\nrole clear_up_trash -> ".$rr." rows\n\n");
                    $trash = ($rr > 0)?' почищено мусора '.$rr:"" ;
                }
                $this->print_json(($result['code'] == 200),$result['msg'].$trash);
                break;
                
                
                
            case 'get_users_tab':
                echo $this->user_profiles->get_users_table();
                break;
            case 'get_role_tab':
                echo $this->role_model->get_roles_table();
                break;
            case 'get_tree_all':
                echo $this->tree_model->get_tree_directory_with_chek();
                break;
            case 'get_tree_child':
                echo $this->tree_model->get_tree_node_with_chek($this->uri->segment(4));
                break;
            case 'get_title_permissions_by_roleid':
                //TODO !!!
                /****************************************************/
                /*$permissions = $this->role_model->get_permissions($this->uri->segment(4));
                foreach ($permissions as $node_obj) {
                    echo $node_obj->get_title_full().'<br>';
                }*/
                
                
                
                
                
//                $role = new Role_model();
//                echo $role->get_title_permissions_by_roleid($this->uri->segment(4));
                
                echo 'not realese';
                break;
            case 'get_title_permission_by_uuid':
//                $tree = new Tree_model();
//                echo $tree->get_title_from_uuid($this->uri->segment(4));
//                echo $this->uri->segment(4);
                echo 'not realese';
                break;
            case 'get_titles_by_uuids_ary':
                $permissions = $this->role_model->get_permissions($this->uri->segment(4));
                foreach ($permissions as $node_obj) {
                    echo $node_obj->get_title_full()."\n";
                }
                break;
            case 'get_title_list':
                $permissions = $this->role_model->get_permissions($this->uri->segment(4));
                foreach ($permissions as $node_obj) {
                    echo $node_obj->get_title_full()."\n";
                }
                break;
            case 'get_users_by_role':
                echo count($this->user_profiles->get_users_by_roleid($this->uri->segment(4)));
                break;
            case 'get_file_users': //получить файл с пользовательскими паролями
                echo $this->user_profiles->get_user_file();
                break;
            case 'save_file_users': //сохранить файл с пользовательскими паролями
                $ary = $this->user_profiles->save_user_file(filter_input(INPUT_POST, 'filePwd'));
                header('Content-type: application/json');
                echo json_encode($ary);
                break;
            case 'get_md5': //сгенерить хеш
                $str = md5($this->uri->segment(4));
                $this->print_json(TRUE, $str);
                break;
            case 'start_update_db': //обновление структуры
                $this->print_json($this->start_update_db());
                break;
            case 'get_status_update_db': //проверка прогресса обновления
                $res = $this->get_status_update_db();
                $this->print_json((gettype($res) === "integer"), $res);
                break;
            default: //метод по умолчанию
                echo $this->get_json(FALSE,'Wrong request');
                break;
         }
    }
    
    /**!!!
     * Print JSON
     * @param bool $result
     * @param string $message
     * @return void JSON string
     */
    private function print_json($result, $message = null) {
        $json['code'] = (boolean) $result ? 200 : 0;
        if (!empty($message)){ 
            $json['msg'] = $message;
        }elseif($json['code'] === 200){
            $json['msg'] = 'Ok';
        }
        header('Content-type: application/json');
        echo json_encode($json);
    }
    
    /**
     * Запуск обновления структуры
     * @return boolean
     */
    private function start_update_db() {
        if ($this->role_model->isAdminRole()) {
            $script = $this->config->item('path_script_update_db_sh');
            shell_exec("nohup " . $script . " >/dev/null 2>&1 &");
            return true;
        } else {
            return false;
        }
    }
    
    //тестовая, для проверки статус бара не затрагивая саму структуру
    private function get_status_update_db2() {
        $sec = (int)date('s');
        $ary = 30;
        $last_el = $sec > $ary+10? $sec/2:$sec;
        
        $percent = floor(($last_el / $ary) * 100);
        return (int)round($percent < 10 ? 10 : $percent);
    }
    
    /**
     * Получение статуса обновления структуры
     * @return int|string
     */
    private function get_status_update_db() {
        $file = trim(file_get_contents($this->config->item('path_result_update_db_dat')));
        if (strlen($file) == 0) {
            return 'No data';
        }

        $ary = explode("\n", $file);
        $last_el = $ary[count($ary) - 1];
        if ($last_el == 'rename_files') {
            return 5;
        } elseif ($last_el == 'rename_dirs') {
            return 7;
        } elseif (preg_match('/[0-9]+/', $last_el)) {
            if (count($ary) == 1){
                return 9;
            }else {
                $percent = floor(($last_el / $ary[0]) * 100);
                return (int)round($percent < 10 ? 10 : $percent);
            }
        } else {
            return '' . $last_el;
        }
    }

}
